//
//  BGAuctionTableViewController.m
//  bigMall
//
//  Created by LTOVE on 16/8/15.
//  Copyright © 2016年 thinklev. All rights reserved.
//

#import "BGAuctionTableViewController.h"
#import "DropdownMenu.h"
#import "BGShopTableViewCell.h"

#import "BGDateResult.h"
#import "BGShopDataModel.h"

#import "BGFenLeiModel.h"
#import "BGTwoLevelDataModel.h"
#import "MJRefresh.h"

#import "BGAreaResultModel.h"
#import "BGAreaDataModel.h"
#import "MJExtension.h"
//#define _pageNum @"7"
#import "BGShopCellModel.h"
#import "BGGoodInfoViewController.h"

#import "BGTenderAuctionModel.h"
#import "BGAuctionInfoViewController.h"

#import "MBProgressHUD.h"
#import "MBProgressHUD+MJ.h"

@interface BGAuctionTableViewController ()<dropdownDelegate>{
    NSArray *_titleArray;
    NSArray *_leftArrat;
    NSArray *_rightArray;
    DropdownMenu *dropdowm;
    NSMutableArray *_dataArray;
    NSUInteger _thisPage;
    NSUInteger _allPage;
    NSString *_catId;
    NSString *_province;
    NSString *_order;
    NSString *_pageNum;
    NSArray *F_oneArray;
    NSArray *F_twoArray;
    NSArray *_areaArray;
    
}

@end

@implementation BGAuctionTableViewController

- (instancetype)init
{
    if (self = [super init]) {
        
        _pageNum = @"10";
        _order = @"id";
        _province = @"";
        _catId = @"";
        _thisPage = 1;
        NSString *path = [[NSBundle mainBundle]pathForResource:@"area.plist" ofType:nil];
        NSArray *array = [NSArray arrayWithContentsOfFile:path];
        array = [array firstObject];
        NSMutableArray *oneArray = [NSMutableArray new];
        NSMutableArray *twoArray = [NSMutableArray new];
        for (NSDictionary *model  in array) {
            NSDictionary *dic = @{
                                  @"idStr":model[@"id"],
                                  @"title":model[@"name"]
                                  };
            
            [oneArray addObject:dic];
        }
        [twoArray addObject:oneArray];
        _areaArray = twoArray;
        
    }
    
    return self;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self loadDropMenu];
    
    self.tableView.contentInset = UIEdgeInsetsMake(40, 0, 49, 0);
    
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadData)];
    
    
    [self.tableView.header beginRefreshing];
    
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],UITextAttributeTextColor,nil]];
    
    //    GWLog(@"%f",self.tableView.height);
    //    self.tableView.height = 100;
    
}

- (NSArray *)getModelWithBGShopModel:(NSArray *)array
{
    NSMutableArray *dataArray = [NSMutableArray array];
    for (BGShopCellModel *model in array) {
        
        BGTenderAuctionModel *TAModel = [[BGTenderAuctionModel alloc ]init];
        TAModel.title = model.title;
//        TAModel.iScaiFen = [model.caiFen isEqualToString:@"是"];
        TAModel.iScaiFen = YES;
        TAModel.time = model.add_time;
        NSString *price = [NSString stringWithFormat:@"报盘价:%@元/%@",model.priceNow,model.unit];
        TAModel.price = price;
        TAModel.Num = [NSString stringWithFormat:@"库存%@%@",model.kuCun,model.unit];
        TAModel.imageOne = @"add.png";
        TAModel.Add = [NSString stringWithFormat:@"交货地:%@",model.addr];
        TAModel.imageTwo = @"date.png";
        TAModel.jiaoHuoFangShi = [NSString stringWithFormat:@"交货方式:%@",model.jiaoHuoFangShi];
        TAModel.guaDanFangShi = model.GuaDanFangShi;
        [dataArray addObject:TAModel];
    }
    
    return dataArray;
}

- (void)loadDropMenu
{
    
    //加载分类列表
    [self loadFenleiData];
    //    //加载地区列表
    //    [self loadAreaData];
}
//加载分类
- (void)loadFenleiData
{
    [BGDateResult loadFenLeiWithLevel:@"level" key:@"no" success:^(NSObject *result) {
        
        BGFenLeiModel *model = (BGFenLeiModel *)result;
        
        NSMutableArray *OneArray = [NSMutableArray new];
        NSMutableArray *F_twoArrays = [NSMutableArray new];
        
        for (BGTwoLevelDataModel *dataModel in model.res) {
            
            [OneArray addObject:dataModel.title];
            NSMutableArray *libianArray = [NSMutableArray new];
            for (BGTwoLevelDataModel *rightModel in dataModel.children) {
                NSDictionary *dict = @{
                                       @"catId":rightModel.catId,
                                       @"title":rightModel.title
                                       };
                [libianArray addObject:dict];
            }
            [F_twoArrays addObject:libianArray];
            
        }
        F_oneArray = OneArray;
        //        [_areaArray writeToFile:@"/Users/LTOVE/Desktop/xcxx.plist" atomically:YES];
        F_twoArray = F_twoArrays;
        
        [self testData];
        [self.tableView reloadData];
        NSLog(@"%lu",(unsigned long)F_oneArray.count);
        //        [_areaArray writeToFile:@"/Users/LTOVE/Desktop/xcxx.plist" atomically:YES];
        
        dropdowm = [[DropdownMenu alloc]initDropdownWithButtonTitles:_titleArray andLeftListArray:_leftArrat andRightListArray:_rightArray];
//        dropdowm.view.height = dropdowm.view.height - 64;
        dropdowm.delegate = self;
        self.tableView.contentInset = UIEdgeInsetsMake(40, 0, 49, 0);
        //    [self.view addSubview:dropdowm.view];
        [[UIApplication sharedApplication].keyWindow addSubview:dropdowm.view];
        
        
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.height = 40;
        btn.width = 40;
        [btn setImage:[UIImage imageWithColor:[UIColor clearColor] size:btn.size] forState:UIControlStateNormal];
        btn.x = screenW - 50;
        btn.centerY = 64 * 0.5;
        [btn addTarget:self action:@selector(resetAndReferch) forControlEvents:UIControlEventTouchUpInside];
        
        [dropdowm.view addSubview:btn];
        
    } failure:^(NSError *error) {
        
        
    }];
}
- (void)resetAndReferch
{
    _order = @"id";
    _province = @"";
    _catId = @"";
    [self refresh];
}

-(void)loadMoreData
{
    //    NSLog(@"dadsa");
    //    NSLog(@"%ld",_allPage);
    //    NSLog(@"%ld",_thisPage);
    if (_thisPage > _allPage) {
        
        [self.tableView.footer endRefreshingWithNoMoreData];
        
        return;
    }
    [MBProgressHUD showMessage:@"加载中..."];
    [BGDateResult auctionListWithCatId:_catId province:_province order:_order thisPage:[NSString stringWithFormat:@"%ld",(unsigned long)_thisPage] pageNum:_pageNum  success:^(NSObject *resultData) {
        [MBProgressHUD hideHUD];
        BGShopDataModel *model = (BGShopDataModel *)resultData;
        [self.tableView.footer endRefreshing];
        [_dataArray addObjectsFromArray:model.list];
        
//        [self.dateArray addObject:[self getModelWithBGShopModel:model.list]];
        [self.dateArray addObjectsFromArray:[self getModelWithBGShopModel:model.list]];
//        [self.dateArray writeToFile:@"/Users/LTOVE/Desktop/百度地图/x.plist" atomically:YES];
//        NSLog(@"%lu",(unsigned long)self.dateArray.count);
//        self.tableView.contentInset = UIEdgeInsetsMake(40, 0, 49, 0);
        [self.tableView reloadData];
        if (model.list.count) {
            
            _thisPage++;
        }
        
    } failure:^(NSError *error) {
        
        [MBProgressHUD hideHUD];
    }];
    //    [self.tableView.footer endRefreshingWithNoMoreData];-
    
}
- (void)loadData
{
    //    if (!_dataArray.count) {
    //        _thisPage = 1;
    //    }
    [MBProgressHUD showMessage:@"加载中..."];
    [BGDateResult auctionListWithCatId:_catId province:_province order:_order thisPage:@"1" pageNum:_pageNum  success:^(NSObject *resultData) {
        [MBProgressHUD hideHUD];
        //        [self.tableView mj_header];
        [self.tableView.header endRefreshing];
        
        
        BGShopDataModel *model = (BGShopDataModel *)resultData;
        //        NSLog(@"%@",model.keyValues);
        _dataArray =(NSMutableArray *) model.list;
        self.dateArray = [[NSMutableArray alloc]initWithArray:[self getModelWithBGShopModel:model.list]];
        
        if ([model.allPage integerValue] > _thisPage) {
            self.tableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
            _thisPage = 2;
            _allPage = [model.allPage integerValue];
        }
        //        _thisPage ++;
        
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        
        [MBProgressHUD hideHUD];
    }];
}

/**
 *  刷新表格
 */
- (void)refresh {
    
    [self.tableView.header beginRefreshing];
    
}
#warning 一下为测试数据

- (void)viewWillDisappear:(BOOL)animated {
    
    dropdowm.view.hidden = YES;
    
}

- (void)viewWillAppear:(BOOL)animated {
    
    dropdowm.view.hidden = NO;
    
}

//测试数据
- (void)testData {
    [self testTitleArray];
    [self testLeftArray];
    [self testRightArray];
    
}

- (void) testTitleArray {
    _titleArray = @[@"分类", @"地区", @"排序"];
}

//左边列表可为空，则为单下拉菜单，可以根据需要传参
- (void)testLeftArray {
    //    NSArray *One_leftArray = @[@"附近", @"熱門商區", @"香洲區", @"斗門區", @"金灣區"];
    
    NSArray *Two_leftArray = [[NSArray alloc] init];
    //    NSArray *R_leftArray = @[@"Test1", @"Test2"];
    NSArray *Three_leftArray = [[NSArray alloc] init];
    
    _leftArrat = [[NSArray alloc] initWithObjects:F_oneArray, Two_leftArray,Three_leftArray, nil];
}
//右边列表不可为空
- (void)testRightArray {
    NSArray *F_rightArray = F_twoArray;
    NSArray *Three_rightArray = @[
                                  @[
                                      @{@"title":@"时间"},
                                      @{@"title":@"价格"},
                                      @{@"title":@"库存"}
                                      ] ,
                                  @[
                                      @{@"title":@"four"}
                                      ]
                                  ];
    
    _rightArray = [[NSArray alloc] initWithObjects:F_rightArray, _areaArray,Three_rightArray, nil];
}
//实现代理，返回选中的下标，若左边没有列表，则返回0
- (void)dropdownSelectedButtonIndex:(NSString *)index LeftIndex:(NSString *)left RightIndex:(NSString *)right {
    NSLog(@"%s : You choice button %@, left %@ and right %@", __FUNCTION__, index, left, right);
    
    int intLeft,intright;
    NSArray *daArray;
    NSDictionary *daDic;
    switch ([index intValue]) {
        case 0:
            
            intLeft = [left intValue];
            intright = [right intValue];
            daArray = F_twoArray[intLeft];
            daDic = daArray[intright];
            _catId = daDic[@"catId"];
            [self refresh];
            break;
        case 1:
            intright = [right intValue];
            daArray = [_areaArray firstObject];
            daDic = daArray[intright];
            _province = daDic[@"idStr"];
            [self refresh];
            
            break;
        case 2:
            switch ([right intValue]) {
                case 0:
                    _order = @"id";
                    [self refresh];
                    break;
                case 1:
                    _order = @"price";
                    [self refresh];
                    break;
                case 2:
                    _order = @"number";
                    [self refresh];
                    break;
                    
                default:
                    break;
            }
            
        default:
            break;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 108;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //    NSLog(@"%@",indexPath);
    BGAuctionInfoViewController *vc = [[BGAuctionInfoViewController alloc]init];
    vc.navigationItem.title = @"拍卖详情";
    vc.hidesBottomBarWhenPushed = YES;
    BGShopCellModel *model = _dataArray[indexPath.row];
    vc.goodId = model.id;
    vc.unit = model.unit;
    //    GWLog(@"%@",model.unit);
    
    //    vc.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    //    self.navigationController.navigationBar.backItem.title = @"";
    //    [self.navigationItem.backBarButtonItem setTitle:@""];
    UIBarButtonItem *back = [[UIBarButtonItem alloc] init];
    back.title = @"";
    self.navigationItem.backBarButtonItem = back;
    
    [self.navigationController pushViewController:vc animated:YES];
}
@end
